#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef double db;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout);
#define pb push_back

inline int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}
const int MAXN = 1<<9;
const int MAXL = 1010;
const int inf = 0x3f3f3f3f;

int n,t[MAXL],b[MAXL];
int f[2][MAXN][20];

inline void getmin(int &x,int y){x = min(x,y);}

inline int calc(int x,int y){return (x | y) - (x & y);}

int main (){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
#endif
	int T = in;
	while(T--){
		n = in; for(int i = 1;i <= n;i++) t[i] = in , b[i] = in;
		int o = 0; memset(f[o],0x3f,sizeof(f[o])); f[o][0][7] = 0;
		for(int i = 1;i <= n;i++,o ^= 1){
			for(int j = 0;j < 1 << 8;j++)
				for(int las = 0;las < 16;las++)
					if(f[o][j][las] < inf){
						int ner = inf;
						for(int k = 0;k <= 7 && k + i <= n;k++){
							if(!(j >> k & 1)){
								if(ner < k) continue;
								ner = min(ner,b[k+i]+k);
								getmin(f[o][j | (1<<k)][k+8],f[o][j][las] + ((i + las - 8) ? calc(t[k+i],t[i+las-8]):0));
							}
						}
					}
			memset(f[o^1],0x3f,sizeof(f[o^1]));
			for(int j = 0;j < 1 << 8;j++)
				if(j & 1)
					for(int las = 1;las < 16;las++)
						getmin(f[o^1][j>>1][las-1],f[o][j][las]);
		}
		int ans = inf;
		for(int j = 0;j < 16;j++) ans = min(ans,f[o][0][j]);
		printf("%d\n",ans);
	}
	return 0;
}
